package cn.e3mall.search.Listener;

import cn.e3mall.common.pojo.SearchItem;
import cn.e3mall.search.mapper.ItemMapper;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.io.IOException;

/**
 * 接收activemq消息
 */
@Service
public class ItemAddMessageListener implements MessageListener {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private SolrServer solrServer;

    @Override
    public void onMessage(Message message) {
        try {
            //1.从消息中取出商品ID
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            Long itemId = Long.valueOf(text);
            //2.根据商品ID获取商品详情
            SearchItem searchItem = null;
            //有可能还没有提交事务，因此这里是有可能取不到商品信息
            //的，为了避免这种情况出现，我们最好等待事务提交，这里
            //我采用3次尝试的方法，每尝试一次休眠一秒
            for(int i = 0; i<3;i++){
                try {
                    Thread.sleep(1000);//休眠1秒
                    searchItem = itemMapper.getItemById(itemId);
                    //如果能获取到商品信息，就退出循环
                    if(searchItem != null){
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //3.创建文档对象
            SolrInputDocument document = new SolrInputDocument();
            //4.向文档对象中添加域
            document.setField("id", searchItem.getId());
            document.setField("item_title", searchItem.getTitle());
            document.setField("item_sell_point", searchItem.getSell_ponit());
            document.setField("item_price", searchItem.getPrice());
            document.setField("item_image", searchItem.getImage());
            document.setField("item_category_name", searchItem.getCategroy_name());
            //5.将文档写入索引库
            solrServer.add(document);
            //6.提交
            solrServer.commit();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
